<?php
declare (strict_types = 1);

namespace app\api\model;

use think\Model;

class ProductGroup extends Model
{
    // 设置表名
    protected $name = 't_product_group';
    
    // 设置主键
    protected $pk = 'id';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    // 设置时间字段
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';

    // 类型转换
    protected $type = [
        'status'      => 'integer',
        'create_time' => 'integer',
        'update_time' => 'integer',
    ];

    /**
     * 关联主图
     */
    public function mainImage()
    {
        return $this->belongsTo('app\api\model\SysFile', 'main_img', 'id');
    }

    /**
     * 获取产品组列表
     * @param int $page
     * @param int $limit
     * @return array
     */
    public static function getList(int $page = 1, int $limit = 10): array
    {
        $query = self::with(['mainImage' => function($query) {
                $query->field('id,file_url');
            }])
            ->whereNull('delete_time')
            ->order('create_time', 'desc');

        $total = $query->count();
        $list = $query->page($page, $limit)->select();

        $data = [];
        foreach ($list as $item) {
            $data[] = [
                'id' => $item->id,
                'name' => $item->name,
                'image_url' => $item->mainImage->file_url ?? '',
                'create_time' => $item->create_time
            ];
        }

        return [
            'total' => $total,
            'list' => $data,
            'page' => $page,
            'limit' => $limit
        ];
    }
} 